<template>
  <div class="form-canvas" @drop="handleDrop" @dragover="handleDragOver">
    <div class="canvas-content">
      <el-form
        ref="formRef"
        :model="formModel"
        :label-width="config.labelWidth"
        :label-position="config.labelPosition"
        class="preview-form"
      >
        <draggable
          v-model="internalFormItems"
          item-key="id"
          class="draggable-area"
          ghost-class="ghost"
          @start="dragging = true"
          @end="dragging = false"
        >
          <template #item="{ element, index }">
            <div
              class="form-item-wrapper"
              :class="{ selected: selectedItem?.id === element.id }"
              @click="handleItemClick(element)"
            >
              <!-- 修改的组件渲染部分开始 -->
              <component
                :is="getComponent(element.type)"
                v-model="formModel[element.model]"
                v-bind="getComponentProps(element)"
              >
                <!-- 处理章节标题和段落的内容 -->
                <template v-if="element.type === 'section'">
                  {{ element.options.title }}
                </template>
                <template v-else-if="element.type === 'paragraph'">
                  {{ element.options.content }}
                </template>
                <template v-else-if="element.type === 'signature'">
                  <div style="min-height: 80px; border-bottom: 1px solid #000; margin: 20px 0">
                    {{ element.options.label }}
                  </div>
                </template>

                <!-- 处理选项型组件的子组件 -->
                <template v-if="['radio', 'checkbox'].includes(element.type)">
                  <component
                    v-for="child in getComponentProps(element).children"
                    :key="child.props.label"
                    :is="child.component"
                    v-bind="child.props"
                  >
                    {{ child.children }}
                  </component>
                </template>

                <!-- 处理下拉选择的选项 -->
                <template v-else-if="element.type === 'select'">
                  <el-option
                    v-for="option in element.options.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </template>
              </component>
              <!-- 修改的组件渲染部分结束 -->

              <div class="item-actions">
                <el-button type="danger" size="small" text @click="removeItem(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
        </draggable>

        <div v-if="!internalFormItems.length" class="empty-canvas">
          <el-icon><Plus /></el-icon>
          <p>拖拽左侧组件到此处</p>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, computed, nextTick } from 'vue'
import draggable from 'vuedraggable'
import { Delete, Plus } from '@element-plus/icons-vue'
import { getElementByType } from '../utils/formElements.js'

// 动态导入Element Plus组件
const componentMap = {
  input: 'el-input',// 单行文本
  textarea: 'el-input',// 多行文本
  number: 'el-input-number',// 数字输入
  select: 'el-select',// 下拉选择
  radio: 'el-radio-group',// 单选框组
  checkbox: 'el-checkbox-group',//  多选框组
  date: 'el-date-picker',// 日期选择
  switch: 'el-switch',// 开关
  section: 'div', // 章节标题
  paragraph: 'div', // 文本段落
  divider: 'el-divider', // 分割线
  signature: 'div', // 签名区域
}

export default {
  name: 'FormCanvas',
  components: {
    draggable,
    Delete,
    Plus,
  },
  props: {
    formItems: {
      type: Array,
      default: () => [],
    },
    selectedItem: {
      type: Object,
      default: null,
    },
  },
  emits: ['select', 'update:form-items'],
  setup(props, { emit }) {
    const internalFormItems = computed({
      get: () => props.formItems,
      set: (value) => emit('update:form-items', value),
    })

    const formModel = ref({})
    const dragging = ref(false)
    const config = ref({
      labelWidth: '100px',
      labelPosition: 'right',
    })

    const handleDragOver = (event) => {
      event.preventDefault()
    }

    const handleDrop = (event) => {
      event.preventDefault()
      const data = JSON.parse(event.dataTransfer.getData('text/plain'))
      addFormElement(data)
    }

    const addFormElement = (element) => {
      const newItem = {
        ...JSON.parse(JSON.stringify(element)),
        id: generateId(),
        model: `field_${Date.now()}`,
      }
      internalFormItems.value.push(newItem)

      // 自动选中新添加的元素
      nextTick(() => {
        handleItemClick(newItem)
      })
    }

    const handleItemClick = (item) => {
      emit('select', item)
    }

    const removeItem = (index) => {
      const removedItem = internalFormItems.value[index]
      internalFormItems.value.splice(index, 1)

      // 如果删除的是当前选中的元素，清空选中状态
      if (props.selectedItem?.id === removedItem.id) {
        emit('select', null)
      }
    }

    const getComponent = (type) => {
      return componentMap[type] || 'el-input'
    }

    const getComponentProps = (element) => {
      const props = { ...element.options }

      // 特殊处理一些组件的属性
      switch (element.type) {
        case 'textarea':
          props.type = 'textarea'
          break
        case 'select':
          props.placeholder = props.placeholder || '请选择'
          break
        case 'radio':
        case 'checkbox':
          // 处理选项
          props.children =
            props.options?.map((option) => ({
              component: element.type === 'radio' ? 'el-radio' : 'el-checkbox',
              props: {
                label: option.value,
              },
              children: option.label,
            })) || []
          break
        case 'section':
          // 章节标题特殊处理
          props.style = {
            fontSize: props.level === 1 ? '24px' : props.level === 2 ? '20px' : '16px',
            fontWeight: 'bold',
            margin: '20px 0 10px 0',
            color: '#303133',
          }
          break
        case 'paragraph':
          // 文本段落特殊处理
          props.style = {
            lineHeight: '1.6',
            margin: '10px 0',
            color: '#606266',
          }
          break
        case 'signature':
          // 签名区域特殊处理
          props.style = {
            borderTop: '1px solid #dcdfe6',
            paddingTop: '20px',
            marginTop: '20px',
            textAlign: 'center',
          }
          break
      }

      return props
    }

    const generateId = () => {
      return `form_item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    }

    return {
      internalFormItems,
      formModel,
      dragging,
      config,
      handleDragOver,
      handleDrop,
      handleItemClick,
      removeItem,
      getComponent,
      getComponentProps,
    }
  },
}
</script>

<style scoped>
.form-canvas {
  height: 100%;
  min-height: 600px;
}

.canvas-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
  min-height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.draggable-area {
  min-height: 400px;
}

.form-item-wrapper {
  position: relative;
  padding: 12px;
  margin-bottom: 16px;
  border: 2px solid transparent;
  border-radius: 4px;
  transition: all 0.3s;
}

.form-item-wrapper:hover {
  border-color: #e0f0ff;
  background: #f5faff;
}

.form-item-wrapper.selected {
  border-color: #409eff;
  background: #f0f7ff;
}

.item-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.form-item-wrapper:hover .item-actions {
  opacity: 1;
}

.empty-canvas {
  text-align: center;
  padding: 60px 20px;
  color: #c0c4cc;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
}

.empty-canvas .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.ghost {
  opacity: 0.5;
  background: #f0f7ff;
}
</style>
